import { defineStore } from 'pinia'
import { emitter } from '@/emitter/emitter'
import { HomeOutline } from '@vicons/ionicons5'
export const useTabStore = defineStore(
  'tabList',
  () => {
    //收集所有的tab
    const tabs = ref<App.Global.Tab[]>([])
    //首页tab
    const homeTab = ref<App.Global.Tab>({
      id: '/home',
      label: '首页',
      fullPath: import.meta.env.VITE_ROUTE_HOME,
      icon: HomeOutline as any
    })
    //当前激活的tab
    const activeTabId = ref<string>(homeTab.value.id)
    //当前激活的tab
    const activeTab = computed(() => tabs.value.find((item) => item.id === activeTabId.value))
    //设置激活的tab
    const setActiveTab = (id: string) => {
      activeTabId.value = tabs.value.find((item) => item.id === id)?.id || ''
    }
    //添加tab
    const addTab = (tab: App.Global.Tab) => {
      if (tabs.value.some((item) => item.id === tab.id)) {
        return
      }
      tabs.value.push(tab)
      setActiveTab(tab.id)
    }
    //移除tab
    const removeTab = (id: string) => {
      if (id === homeTab.value.id) {
        emitter.emit('TAB_CLOSE_LAST')
        return
      }
      const index = tabs.value.findIndex((item) => item.id === id)
      if (index === -1) {
        return
      }
      tabs.value.splice(index, 1)
      if (activeTabId.value === id) {
        const prevTab = tabs.value[index - 1] || homeTab.value
        activeTabId.value = prevTab.id
      }
    }
    //退出后移除所有tab
    const removeAfterLeave = () => {
      tabs.value = []
      activeTabId.value = homeTab.value.id
    }
    return {
      tabs,
      homeTab,
      activeTabId,
      activeTab,
      setActiveTab,
      addTab,
      removeTab,
      removeAfterLeave
    }
  },
  {
    persist: true
  }
)
